/**
 * 贴图管理路由
 * 支持中文文件名，每个贴图独立保存配置文件
 */
const express = require('express');
const router = express.Router({ mergeParams: true }); // 允许访问父路由参数
const fs = require('fs').promises;
const fsSync = require('fs');
const path = require('path');
const multer = require('multer');
const { imageSize: sizeOf } = require('image-size'); // ⭐ 修复：使用新版本的导入方式
const { PROJECTS_DIR } = require('../utils/constants');
const { generateId } = require('../utils/helpers');
const { readProjectsIndex } = require('../services/projectService');
const {
    readTextureConfig,
    writeTextureConfig,
    deleteTextureConfig,
    getAllTextures,
    updateTextureReference
} = require('../utils/textureConfigHelper');

// 配置文件上传 - 使用ID作为文件名避免中文乱码
const storage = multer.diskStorage({
    destination: async (req, file, cb) => {
        try {
            const projectId = req.params.id;
            const index = await readProjectsIndex();
            const projectMeta = index.projects.find(p => p.id === projectId);
            
            if (!projectMeta) {
                return cb(new Error('项目不存在'));
            }
            
            const texturesDir = path.join(PROJECTS_DIR, projectMeta.path, 'textures');
            // 确保目录存在
            await fs.mkdir(texturesDir, { recursive: true });
            cb(null, texturesDir);
        } catch (error) {
            cb(error);
        }
    },
    filename: (req, file, cb) => {
        // 使用贴图ID作为文件名，避免中文乱码
        const textureId = generateId('texture');
        const ext = path.extname(file.originalname);
        
        // 将textureId存储在req中，供后续使用
        if (!req.textureIds) {
            req.textureIds = {};
        }
        req.textureIds[file.fieldname] = textureId;
        
        cb(null, `${textureId}${ext}`);
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 10 * 1024 * 1024 // 限制10MB
    },
    fileFilter: (req, file, cb) => {
        // 只允许图片文件
        const allowedTypes = /jpeg|jpg|png|gif|webp|bmp/;
        const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
        const mimetype = allowedTypes.test(file.mimetype);
        
        if (extname && mimetype) {
            console.log(`✅ [Texture Upload] 接收文件: ${file.originalname}`);
            return cb(null, true);
        } else {
            cb(new Error('只允许上传图片文件 (jpeg, jpg, png, gif, webp, bmp)'));
        }
    }
});

/**
 * 获取所有贴图列表
 * GET /api/projects/:id/textures
 */
router.get('/', async (req, res) => {
    try {
        const { id } = req.params;
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const texturesDir = path.join(PROJECTS_DIR, projectMeta.path, 'textures');
        
        // 确保目录存在
        await fs.mkdir(texturesDir, { recursive: true });
        
        // 读取所有贴图配置
        const textures = await getAllTextures(texturesDir);
        
        // 为每个贴图添加完整的访问路径
        const texturesWithFullPath = textures.map(texture => ({
            ...texture,
            url: `/projects/${projectMeta.path}/textures/${texture.id}${texture.ext}`
        }));
        
        res.setHeader('Content-Type', 'application/json; charset=utf-8');
        res.json({
            success: true,
            data: texturesWithFullPath
        });
        
    } catch (error) {
        console.error('❌ 获取贴图列表失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取单个贴图信息
 * GET /api/projects/:id/textures/:textureId
 */
router.get('/:textureId', async (req, res) => {
    try {
        const { id, textureId } = req.params;
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const texturesDir = path.join(PROJECTS_DIR, projectMeta.path, 'textures');
        const texture = await readTextureConfig(texturesDir, textureId);
        
        if (!texture) {
            return res.status(404).json({
                success: false,
                error: '贴图不存在'
            });
        }
        
        res.json({
            success: true,
            data: {
                ...texture,
                url: `/projects/${projectMeta.path}/textures/${texture.id}${texture.ext}`
            }
        });
    } catch (error) {
        console.error('❌ 获取贴图信息失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 上传贴图
 * POST /api/projects/:id/textures/upload
 * Form-data: texture (file), originalFileName (可选，用于修复中文文件名)
 */
router.post('/upload', upload.single('texture'), async (req, res) => {
    try {
        const { id } = req.params;
        const { originalFileName } = req.body;
        
        if (!req.file) {
            return res.status(400).json({
                success: false,
                error: '未上传文件'
            });
        }
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const texturesDir = path.join(PROJECTS_DIR, projectMeta.path, 'textures');
        
        // 使用multer存储时生成的贴图ID
        const textureId = req.textureIds ? req.textureIds['texture'] : generateId('texture');
        
        // ⭐ 关键：优先使用前端传来的正确文件名，避免使用被浏览器编码的originalname
        const correctFileName = originalFileName || req.file.originalname;
        const ext = path.extname(correctFileName);
        const baseName = path.basename(correctFileName, ext);
        
        console.log(`✅ [Texture Upload] 接收文件: ${correctFileName}${originalFileName ? ' (使用前端修复后的文件名)' : ''}`);
        
        // 📋 检查同名贴图（上传前）- 拒绝上传重名文件
        try {
            const existingTextures = await getAllTextures(texturesDir);
            const duplicateTexture = existingTextures.find(tex => {
                const existingName = tex.displayName || tex.name || '';
                return existingName === baseName;
            });
            
            if (duplicateTexture) {
                console.warn(`⚠️ [Texture Upload] 检测到同名贴图: ${baseName}，拒绝上传`);
                
                // 删除刚上传的重复文件
                try {
                    await fs.unlink(req.file.path);
                } catch (err) {
                    console.warn(`⚠️ 删除重复文件失败: ${err.message}`);
                }
                
                return res.status(400).json({
                    success: false,
                    error: `贴图 "${baseName}" 已存在，无法上传重名文件`
                });
            }
        } catch (error) {
            console.warn(`⚠️ [Texture Upload] 检查同名贴图时出错:`, error.message);
        }
        
        // ⭐ 获取图片尺寸
        let dimensions = { width: null, height: null };
        try {
            const imagePath = req.file.path;
            // image-size 2.x 需要读取文件为Buffer
            const imageBuffer = await fs.readFile(imagePath);
            dimensions = sizeOf(imageBuffer);
            console.log(`📐 [Texture Upload] 图片尺寸: ${dimensions.width} × ${dimensions.height}`);
        } catch (error) {
            console.warn(`⚠️ [Texture Upload] 无法获取图片尺寸:`, error.message);
        }
        
        // 创建贴图配置
        const textureMetadata = {
            id: textureId,
            name: baseName,
            displayName: baseName,
            originalName: correctFileName,
            filename: correctFileName, // 保存原始文件名（含中文）
            ext: ext, // 文件扩展名
            path: `textures/${textureId}${ext}`, // 实际存储路径（使用ID）
            size: req.file.size,
            mimetype: req.file.mimetype,
            width: dimensions.width, // 图片宽度
            height: dimensions.height, // 图片高度
            referenceCount: 0, // 引用计数
            referencedBy: [], // 引用此贴图的材质列表
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        
        // 保存单个贴图配置文件
        await writeTextureConfig(texturesDir, textureId, textureMetadata);
        
        console.log('✅ 贴图上传成功:', textureMetadata.displayName);
        res.json({
            success: true,
            data: {
                ...textureMetadata,
                url: `/projects/${projectMeta.path}/textures/${textureId}${ext}`
            }
        });
        
    } catch (error) {
        console.error('❌ 上传贴图失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取贴图文件
 * GET /api/projects/:id/textures/:textureId/file
 */
router.get('/:textureId/file', async (req, res) => {
    try {
        const { id, textureId } = req.params;
        
        console.log(`\n📥 [Texture File] 请求贴图文件: project=${id}, texture=${textureId}`);
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const texturesDir = path.join(PROJECTS_DIR, projectMeta.path, 'textures');
        const texture = await readTextureConfig(texturesDir, textureId);
        
        if (!texture) {
            return res.status(404).json({
                success: false,
                error: '贴图不存在'
            });
        }
        
        // 构建贴图文件的完整路径
        const textureFilePath = path.join(PROJECTS_DIR, projectMeta.path, texture.path);
        
        console.log(`📂 [Texture File] 贴图文件路径: ${textureFilePath}`);
        
        if (!fsSync.existsSync(textureFilePath)) {
            console.log(`❌ [Texture File] 贴图文件不存在: ${textureFilePath}`);
            return res.status(404).json({
                success: false,
                error: '贴图文件不存在'
            });
        }
        
        console.log(`✅ [Texture File] 返回贴图文件: ${texture.displayName}`);
        
        res.setHeader('Content-Type', texture.mimetype);
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.sendFile(textureFilePath);
        
    } catch (error) {
        console.error('❌ [Texture File] 获取贴图文件失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 增加贴图引用计数
 * POST /api/projects/:id/textures/:textureId/add-reference
 * Body: { materialId }
 */
router.post('/:textureId/add-reference', async (req, res) => {
    try {
        const { id, textureId } = req.params;
        const { materialId } = req.body;
        
        if (!materialId) {
            return res.status(400).json({
                success: false,
                error: '材质ID不能为空'
            });
        }
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const texturesDir = path.join(PROJECTS_DIR, projectMeta.path, 'textures');
        const texture = await updateTextureReference(texturesDir, textureId, materialId, 'add');
        
        if (!texture) {
            return res.status(404).json({
                success: false,
                error: '贴图不存在'
            });
        }
        
        console.log(`✅ 贴图引用计数增加: ${textureId} -> ${texture.referenceCount}`);
        res.json({
            success: true,
            data: texture
        });
        
    } catch (error) {
        console.error('❌ 增加引用计数失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 减少贴图引用计数
 * POST /api/projects/:id/textures/:textureId/remove-reference
 * Body: { materialId }
 */
router.post('/:textureId/remove-reference', async (req, res) => {
    try {
        const { id, textureId } = req.params;
        const { materialId } = req.body;
        
        if (!materialId) {
            return res.status(400).json({
                success: false,
                error: '材质ID不能为空'
            });
        }
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const texturesDir = path.join(PROJECTS_DIR, projectMeta.path, 'textures');
        const texture = await updateTextureReference(texturesDir, textureId, materialId, 'remove');
        
        if (!texture) {
            return res.status(404).json({
                success: false,
                error: '贴图不存在'
            });
        }
        
        console.log(`✅ 贴图引用计数减少: ${textureId} -> ${texture.referenceCount}`);
        res.json({
            success: true,
            data: texture
        });
        
    } catch (error) {
        console.error('❌ 减少引用计数失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 更新贴图信息（名称、描述等）
 * PUT /api/projects/:id/textures/:textureId
 * Body: { name, description }
 */
router.put('/:textureId', async (req, res) => {
    try {
        const { id, textureId } = req.params;
        const { name, description } = req.body;
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const texturesDir = path.join(PROJECTS_DIR, projectMeta.path, 'textures');
        const texture = await readTextureConfig(texturesDir, textureId);
        
        if (!texture) {
            return res.status(404).json({
                success: false,
                error: '贴图不存在'
            });
        }
        
        // 更新字段
        if (name) {
            texture.name = name;
            texture.displayName = name;
        }
        if (description !== undefined) {
            texture.description = description;
        }
        
        await writeTextureConfig(texturesDir, textureId, texture);
        
        console.log('✅ 贴图信息更新成功:', texture.displayName);
        res.json({
            success: true,
            data: texture
        });
        
    } catch (error) {
        console.error('❌ 更新贴图信息失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 删除贴图
 * DELETE /api/projects/:id/textures/:textureId
 */
router.delete('/:textureId', async (req, res) => {
    try {
        const { id, textureId } = req.params;
        
        console.log(`\n🗑️ [Delete Texture] 删除贴图: project=${id}, texture=${textureId}`);
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === id);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const texturesDir = path.join(PROJECTS_DIR, projectMeta.path, 'textures');
        const texture = await readTextureConfig(texturesDir, textureId);
        
        if (!texture) {
            return res.status(404).json({
                success: false,
                error: '贴图不存在'
            });
        }
        
        console.log(`📋 贴图名称: ${texture.displayName}`);
        
        // 检查引用计数
        if (texture.referenceCount > 0) {
            console.log(`⚠️ 贴图仍被 ${texture.referenceCount} 个材质引用`);
            return res.status(400).json({
                success: false,
                error: `贴图仍被 ${texture.referenceCount} 个材质引用，无法删除`,
                referencedBy: texture.referencedBy
            });
        }
        
        // 删除贴图文件
        const textureFilePath = path.join(PROJECTS_DIR, projectMeta.path, texture.path);
        try {
            await fs.unlink(textureFilePath);
            console.log(`✅ 删除贴图文件: ${textureFilePath}`);
        } catch (err) {
            console.warn('⚠️ 删除贴图文件失败:', err.message);
        }
        
        // 删除配置文件
        await deleteTextureConfig(texturesDir, textureId);
        
        console.log('✅ 贴图删除成功:', texture.displayName);
        res.json({
            success: true,
            message: '贴图删除成功'
        });
        
    } catch (error) {
        console.error('❌ 删除贴图失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

module.exports = router;
